--[[
Name: BrownieHelper
Developed by: Sonora (The Dragon Flight)
Website: http://sonora.kirintor.googlepages.com/contents
SVN: http://code.google.com/p/browniehelper/source/browse
License: GNU General Public License v3
]]

--[[

Place holder for future refactoring.

Rightly so, first things first: gnome love.

Needless to say, you ~could~ edit this module to implent other sorts of chat
flavor.
]]

local __version__ = "1.0"

--Whisper commands (ordered and mutually exclusive)
whisperCommands = {
    {
        command = "help?",
        description = "returns the list of available commands",
        handler = function(sender, msg)
            if string.find(msg, "^[Hh]elp%s*?") then
                local lines = {}
                
                table.insert(lines, "~Commands~")
                for i,command in pairs(BrownieHelper:getWhisperCommands()) do
                    --We munge the start of the line, so that anyone running the mod doesn't get a bunch of command triggers
                    if not command.hide then table.insert(lines, " "..command.command.." - "..command.description) end
                end
                
                BrownieHelper:sendWhisperMessage(sender, lines)
                
                return true
            end
        end,
    },
    
    {
        command = "instructions?",
        description = "returns instructions for you about the current auction",
        handler = function(sender, msg)
            if string.find(msg, "^[Ii]nstructions%s*?") then
                local lines = {}
                
                local playerBidSetup = BrownieHelper:getPlayerBidSetup(sender)
                if playerBidSetup then
                    table.insert(lines, "~Current Auction~")
                    table.insert(lines, "Item: "..playerBidSetup.link)
                    table.insert(lines, "Instructions: "..playerBidSetup.instructions)
                    if playerBidSetup.playername~=sender then table.insert(lines, "You're bidding as: "..playerBidSetup.playername) end
                    table.insert(lines, "Your points: "..tostring(playerBidSetup.points))
                    if not playerBidSetup.canbid then
                        table.insert(lines, "Your bid: you cannot place a point bid durring this auction phase.")
                    elseif playerBidSetup.maxbid==playerBidSetup.minbid then
                        table.insert(lines, "Fixed bid: "..tostring(playerBidSetup.minbid))
                    else
                        table.insert(lines, "Your minimum bid: "..tostring(playerBidSetup.minbid))
                        if playerBidSetup.maxbid~=nil then
                            table.insert(lines, "Your maximum bid: "..tostring(playerBidSetup.maxbid))
                        end
                    end
                    
                else
                    lines="There is no auction running right now."
                end
                
                BrownieHelper:sendWhisperMessage(sender, lines)
                
                return true
            end
        end,
    },
    
    {
        command = "points?",
        description = "returns the number of points you have for the current pool",
        handler = function(sender, msg)
            if string.find(msg, "^[Pp]oints%s*?") then
                local poolName, pointsDb = BrownieHelper:getCurrentPointPool()
                if poolName and poolName~="none selected" then
                    BrownieHelper:sendWhisperMessage(sender, {"You have "..tostring(pointsDb[BrownieHelper:getPlayerName(sender)]).." points for "..poolName.."."})
                else
                    BrownieHelper:sendWhisperMessage(sender, {"*looks up from "..BrownieHelper:getPlayerPossesive().." paper work* Sorry, I haven't setup information for the current run yet.  Try back later."})
                end
                return true
            end
        end,
        
    },
    
    {
        command = "raid points?",
        description = "returns the number of points held by each character in the raid",
        handler = function(sender, msg)
            if string.find(msg, "^[Rr]aid%s*[Pp]oints%s*?") then
                local poolName, pointsDb = BrownieHelper:getCurrentPointPool()
                if poolName and poolName~="none selected" then
                    local lines = {"~"..poolName.."~"}
                    for characterName,info in pairs(BrownieHelper:getRoster()) do
                        table.insert(lines,
                            characterName.." - "..tostring(pointsDb[BrownieHelper:getPlayerName(characterName)])
                        )
                    end
                    BrownieHelper:sendWhisperMessage(sender, lines)
                else
                    BrownieHelper:sendWhisperMessage(sender, {"*looks up from "..BrownieHelper:getPlayerPossesive().." paper work* Sorry, I haven't setup information for the current run yet.  Try back later."})
                end
                return true
            end
        end,
    },
    
    {
        command = "bid n",
        description = "place a bid of 'n' points (for example whispering me 'bid 5' will place a bid of 5 points)",
        handler = function(sender, msg)
            local _,_, num = string.find(msg, "^[Bb][Ii][Dd]%s*(%d+)")
            if num~=nil then
                if BrownieHelper:biddingIsOpen() then BrownieHelper:addBid(sender, num)
                else BrownieHelper:sendWhisperMessage(sender, "Sorry there is no auction open for bidding right now.")
                end
                
                return true
            end
        end,
    },
    
    {
        command = "bid all",
        description = "bid the maximum number of points you can in the current auction",
        handler = function(sender, msg)
            if string.find(msg, "^[Bb][Ii][Dd]%s*[Aa][Ll][Ll]") then
                if BrownieHelper:biddingIsOpen() then
                    local playerBidSetup = BrownieHelper:getPlayerBidSetup(sender)
                    if playerBidSetup.maxbid~= nil then BrownieHelper:addBid(sender, playerBidSetup.maxbid)
                    else BrownieHelper:sendWhisperMessage(sender, "Sorry there is maximum bid defined for you -- you must bid by whispering me with a bid number (for example 'bid 10').")
                    end
                else BrownieHelper:sendWhisperMessage(sender, "Sorry there is no auction open for bidding right now.")
                end
                
                return true
            end
        end,
    },
    
    {
        command = "bid none",
        description = "clears any previous bids and rolls for the current auction",
        handler = function(sender, msg)
            if string.find(msg, "^[Bb][Ii][Dd]%s*[Nn][Oo][Nn][Ee]") then
                if BrownieHelper:biddingIsOpen() then BrownieHelper:removeBid(sender)
                else BrownieHelper:sendWhisperMessage(sender, "Sorry there is no auction open for bidding right now.")
                end
                return true
            end
        end,
    },
    
    --These are just here for fun, and this hidden; but I've seen these come in.
    
    {
        command = "bribe?",
        description = "",
        hide = true,
        handler = function(sender, msg)
            if string.find(msg, "^bribe?") then
                BrownieHelper:sendWhisperMessage(sender, "You cannot bribe a gnome.  Or a master looter with the heart of a gnome.")
            end
        end,
    },
    
    --[[this is doing weird things
    {
        command = "beg?",
        description = "",
        hide = true,
        handler = function(sender, msg)
            if string.find(msg, "^beg?") then
                BrownieHelper:sendWhisperMessage(sender, "*smiles warmly*  Really now.  Stand up.")
            end
        end,
    },
    ]]--
    
}

--API
function BrownieHelper:setupWhisperCommands()

    --Keep a list of whisper command handlers
    self.whisperCommands = {}
    
    --Register the whisper command handlers we implement
    for i,command in pairs(whisperCommands) do self:registerWhisperCommand(command) end
    
    --Register for incomming chat commands via whisper
    self:registerEvent("CHAT_MSG_WHISPER", function(message, author) self:receiveWhisperCommand(author, message) end)
    
end
function BrownieHelper:registerWhisperCommand(handler)
    table.insert(self.whisperCommands, handler)
end
function BrownieHelper:getWhisperCommands()
    return self.whisperCommands
end

--Possive table
local possessiveTable = { "its", "his", "her" }
function BrownieHelper:getPlayerPossesive()
    return possessiveTable[UnitSex("player")]
end

--Incomming message handlers
function BrownieHelper:receiveWhisperCommand(sender, msg)
    
    --Let each handler vote on whether or not the message contains its command
    for i,command in pairs(self:getWhisperCommands()) do
        if command.handler(sender, msg) then return true end
    end
    
end

--Outgoing message calls
function BrownieHelper:sendGroupMessage(lines)
    
    if type(lines) == "string" then lines = {lines,} end
    
    --If we're in a raid
    local channel = ""
    if GetNumRaidMembers()>0 then channel = "RAID"
    else channel = "PARTY"
    end
    
    for i,line in pairs(lines) do
        SendChatMessage(line, channel)
    end

end

gnome_salutations = {
    "Rock on my gnomish brother.",
    "Power to the people of appropriate stature.",
    "Gnome power.  *does the secret handshake*",
    "*whispers* Don't tell the tall ones.",
    }

function BrownieHelper:sendWhisperMessage(recipient, lines)

    --Make sure the unit exists
    if not UnitExists(recipient) then return false end

    if type(lines) == "string" then lines = {lines,} end

    local language = GetDefaultLanguage("player")
    
    local playerRace, playerRaceEn = UnitRace("player")
    local recipientRace, recipientRaceEn = UnitRace(recipient) --only works if recipient is in our party or raid
    if playerRaceEn=="Gnome" and recipientRaceEn=="Gnome" then
        language = "GNOMISH"
        table.insert(lines, gnome_salutations[math.random(#gnome_salutations)])
    end
    
    for i,line in pairs(lines) do
        SendChatMessage(line, "WHISPER", language, recipient)
    end
    
end
